module matrix_lru #(
    parameter SIZE = 4,
    parameter INDEX_WIDTH = $clog2(SIZE)
)(
    input clk,
    input rst,
    input update_entry,
    input [INDEX_WIDTH-1:0] update_index, 
    output reg [INDEX_WIDTH-1:0] lru_index
);

reg [SIZE-1:0] matrix [0:SIZE-1];
reg [SIZE-1:0] matrix_nxt [0:SIZE-1];
reg [INDEX_WIDTH-1:0] lru_index_nxt;

generate
    genvar i;
    for (i = 0;i < SIZE; i = i+1) begin
        always @(posedge clk) begin
            if(rst) begin
                matrix[i] <= {SIZE{1'b0}};
            end
            else begin
                matrix[i] <= matrix_nxt[i];
            end
        end

    end
endgenerate

generate
    genvar j,k;
    for (j=0; j<SIZE; j=j+1) begin
        for (k=0; k<SIZE; k=k+1) begin
            always @(*) begin
                matrix_nxt[j][k] = matrix[j][k];
                if(update_entry && (update_index==j) && (update_index!=k))
                    matrix_nxt[j][k] = 1'b1;
                else if(update_entry && (update_index==k))
                    matrix_nxt[j][k] = 1'b0;
            end
        end
    end
endgenerate

generate
    if(SIZE==2) begin
        always @(*) begin 
            lru_index_nxt = lru_index;

            if(matrix[0]==2'b0)
                lru_index_nxt = 'd0;
            else if(matrix[1]==2'b0)
                lru_index_nxt = 'd1;       
        end
    end
    else if(SIZE==4) begin
        always @(*) begin 
            lru_index_nxt = lru_index;

            if(matrix[0]==4'b0)
                lru_index_nxt = 'd0;
            else if(matrix[1]==4'b0)
                lru_index_nxt = 'd1;
            else if(matrix[2]==4'b0)
                lru_index_nxt = 'd2;
            else if(matrix[3]==4'b0)
                lru_index_nxt = 'd3;        
        end
    end
    else if(SIZE==8) begin
        always @(*) begin 
            lru_index_nxt = lru_index;

            if(matrix[0]==8'b0)
                lru_index_nxt = 'd0;
            else if(matrix[1]==8'b0)
                lru_index_nxt = 'd1;
            else if(matrix[2]==8'b0)
                lru_index_nxt = 'd2;
            else if(matrix[3]==8'b0)
                lru_index_nxt = 'd3;
            else if(matrix[4]==8'b0)
                lru_index_nxt = 'd4;
            else if(matrix[5]==8'b0)
                lru_index_nxt = 'd5;
            else if(matrix[6]==8'b0)
                lru_index_nxt = 'd6;
            else if(matrix[7]==8'b0)
                lru_index_nxt = 'd7;                        
        end
    end
endgenerate



always @(posedge clk) begin
    if(rst)
        lru_index <= 'd0;
    else
        lru_index <= lru_index_nxt;
end

endmodule //matrix_lru